package com.ali.protobuf.more;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Random;

/**
 * 自定义客户端处理器
 */
public class MyProtoBufMoreClientHandler extends ChannelInboundHandlerAdapter {
    /**
     * 通道激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        int num = new Random().nextInt(2) + 1;

        MessagePOJO.MessageInfo.Builder messageBuilder = MessagePOJO.MessageInfo.newBuilder();
        if (num == 1) {
            messageBuilder.setDataType(MessagePOJO.MessageInfo.DataType.USER_TYPE);
            MessagePOJO.User.Builder userBuilder = MessagePOJO.User.newBuilder();
            userBuilder.setId(1);
            userBuilder.setCode("zs");
            userBuilder.setName("张三");
            messageBuilder.setUser(userBuilder.build());
        } else {
            messageBuilder.setDataType(MessagePOJO.MessageInfo.DataType.ORDER_TYPE);
            MessagePOJO.Order.Builder orderBuilder = MessagePOJO.Order.newBuilder();
            orderBuilder.setCode("000001");
            orderBuilder.setTime(1704038400000L);
            messageBuilder.setOrder(orderBuilder.build());
        }
        MessagePOJO.MessageInfo messageInfo = messageBuilder.build();
        //写入返回内容
        ctx.write(messageInfo);
        //刷新
        ctx.flush();
    }
}
